package com.camartsApp.controller;

import com.camartsApp.Util.JwtUtils;
import com.camartsApp.Util.Response;
import com.camartsApp.common.PhotoUserVO;
import com.camartsApp.common.ResultVO;
import com.camartsApp.entity.Photo;
import com.camartsApp.service.PhotoService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/photo")
public class PhotoHomeController {
    private static final Logger logger = LoggerFactory.getLogger(PhotoHomeController.class);

    @Autowired
    private PhotoService photoService;

    @Autowired
    private JwtUtils jwtUtils;


    /**
     * 获取所有用户最新上传的照片
     * @return 按上传时间倒序排列的照片列表
     */
    @GetMapping("/new")
    public ResultVO getLatestPhotos() {
        List<Photo> photos = photoService.getLatestPhotos();
        return new ResultVO(ResultVO.SUCCESS, "获取最新照片成功", photos);
    }


    // 优化超时处理
    @GetMapping("/new/async")
    public CompletableFuture<ResultVO> getLatestPhotosAsync() {
        logger.info("接收到异步获取最新照片请求");

        return photoService.getLatestPhotosAsync()
                .thenApply(photos -> {
                    logger.debug("成功获取{}张照片", photos.size());
                    return new ResultVO(ResultVO.SUCCESS, "异步获取最新照片成功", photos);
                })
                .exceptionally(ex -> {
                    logger.error("获取最新照片失败", ex);
                    return new ResultVO(ResultVO.ERROR, "获取最新照片失败: " + ex.getMessage(), null);
                })
                .completeOnTimeout(
                        new ResultVO(ResultVO.TIMEOUT, "请求超时，请重试", null), // 返回null而不是空列表
                        800, TimeUnit.MILLISECONDS
                );
    }

    // 优化缓存接口超时处理
    @GetMapping("/new/cached")
    public CompletableFuture<ResultVO> getCachedLatestPhotosAsync() {
        logger.info("接收到缓存异步获取最新照片请求");

        return photoService.getCachedLatestPhotosAsync()
                .thenApply(photos ->
                        new ResultVO(ResultVO.SUCCESS, "获取缓存最新照片成功", photos)
                )
                .exceptionally(ex -> {
                    logger.error("获取缓存最新照片失败", ex);
                    // 尝试使用同步方法获取数据作为回退
                    List<Photo> fallbackPhotos = photoService.getLatestPhotos();
                    return new ResultVO(ResultVO.ERROR, "获取缓存失败，使用最新数据", fallbackPhotos);
                })
                .completeOnTimeout(
                        new ResultVO(ResultVO.TIMEOUT, "请求超时，使用最新数据", photoService.getLatestPhotos()),
                        800, TimeUnit.MILLISECONDS
                );
    }
    // 从请求头中获取当前用户ID（从Token中解析）
    private Long getCurrentUserId(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            return jwtUtils.getUserIdFromToken(token);
        }
        return null;
    }

    /**
     * 获取点赞数最高的照片列表
     */
    @GetMapping("/greatest")
    public ResultVO getGreatestPhotos() {
        List<Photo> photos = photoService.getGreatestPhotos();
        return new ResultVO(ResultVO.SUCCESS, "获取最热照片成功", photos);
    }

    /**
     * 根据ID查询照片详细信息
     * @param id 照片ID
     * @return 照片详细信息
     */
    @GetMapping("/{id}")
    public ResultVO getPhotoById(@PathVariable("id") String id) {
        Photo photo = photoService.getPhotoById(id);
        if (photo == null) {
            return new ResultVO(ResultVO.FAIL, "照片不存在", null);
        }
        return new ResultVO(ResultVO.SUCCESS, "获取照片信息成功", photo);
    }

    /**
     * 获取照片关联的用户信息
     * @param id 照片ID
     * @return 用户信息
     */
    @GetMapping("/{id}/user")
    public ResultVO getPhotoUser(@PathVariable("id") String id) {
        PhotoUserVO user = photoService.getPhotoUser(id);
        if (user == null) {
            return new ResultVO(ResultVO.FAIL, "照片或用户不存在", null);
        }
        return new ResultVO(ResultVO.SUCCESS, "获取用户信息成功", user);
    }

    @GetMapping("api/{targetPhotoId}/is-liked")
    public ResultVO checkIsLiked(@PathVariable("targetPhotoId") Long targetPhotoId, HttpServletRequest request) {
        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return Response.FailResultByMsg("无效的Token或用户未登录");
        }
        return photoService.checkIsLiked(currentUserId, targetPhotoId);
    }

    @PostMapping("api/{targetPhotoId}/like")
    public ResultVO like(@PathVariable("targetPhotoId") Long targetPhotoId, HttpServletRequest request) {
        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return Response.FailResultByMsg("无效的Token或用户未登录");
        }
        return photoService.like(currentUserId, targetPhotoId);
    }

    @PostMapping("api/{targetPhotoId}/dislike")
    public ResultVO dislike(@PathVariable("targetPhotoId") Long targetPhotoId, HttpServletRequest request) {
        Long currentUserId = getCurrentUserId(request);
        if (currentUserId == null) {
            return Response.FailResultByMsg("无效的Token或用户未登录");
        }
        return photoService.dislike(currentUserId, targetPhotoId);
    }

}
